package com.cisdi.analysis.web.filter;

import com.thetransactioncompany.cors.CORSConfiguration;
import com.thetransactioncompany.cors.CORSConfigurationException;
import com.thetransactioncompany.cors.CORSFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Properties;

/**
 * Cors过滤器
 * @author liujunnan
 * @date 2018/5/23
 */
@WebFilter(filterName = "corsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    /**
     * CORSFilter实例化对象
     */
    private static final CORSFilter CORS_FILTER = new CORSFilter();

    @Override
    public void init(FilterConfig filterConfig) {

        Properties props = new Properties();
        props.setProperty("cors.allowOrigin", "*");
        props.setProperty("cors.supportedMethods", "GET, POST, HEAD, PUT, DELETE, PATCH");
        props.setProperty("cors.supportedHeaders", "Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Authorization");
        props.setProperty("cors.exposedHeaders", "Set-Cookie");
        props.setProperty("cors.supportsCredentials", "true");
        CORSConfiguration config = null;
        try {
            config = new CORSConfiguration(props);
        } catch (CORSConfigurationException e) {
            e.printStackTrace();
        }
        CORS_FILTER.setConfiguration(config);
        logger.info("CorsFilter过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        CORS_FILTER.doFilter(request, response, chain);
    }

    @Override
    public void destroy() {
        logger.info("过滤器销毁");
    }
}
